import {messages, queryCurrencyPrecision } from "share/common";
import React  from 'react'
import { connect } from 'react-redux'
import {Row, Col, Timeline, Button, Spin, Divider, Icon, Anchor} from 'antd'
import columnsListData from './columns-list-data'
import confirmSumptionService from './confirm-consumption.service'
import SlideFrame from "components/slide-frame";
import EditConsumptionDetail from 'containers/confirm-consumption/edit-consumption-detail'
import Apportion from 'containers/confirm-consumption/apportion-frame'
import errorMessage from "share/errorMessage";
const Link = Anchor.Link;

class ConfirmConsumptionDetail extends React.Component{

  state = {
    dataSource: {},
    reasonList: [],
    loading: false,
    animateIcon: 'rotate-before',
    animateList: 'slide-up',
    apportionDTOS: []
  };

  sectionList = {
    baseInfo: messages('common.baseInfo')/*基本信息*/,
    consumption: messages('expense-16.key322')/*消费内容*/,
    costCenter: messages('expense-16.key462')/*订单成本中心*/,
    order: messages('expense-16.key323')/*订单信息*/
  };

  componentWillMount() {
    const { dispenseId, dispenseType } = this.props.params;
    dispenseId && this.getDetail(dispenseId, dispenseType)
  }

  componentWillReceiveProps(nextProps) {
    if((nextProps.params.dispenseId && nextProps.params.dispenseId !== this.props.params.dispenseId) ||
      (nextProps.show && nextProps.show !== this.props.show)) {
      this.getDetail(nextProps.params.dispenseId, nextProps.params.dispenseType)
    }
  }

  getDetail = (dispenseId, dispenseType) => {
    this.setState({ loading: true });
    confirmSumptionService.getSettleByRecordId(dispenseType, dispenseId).then(res => {
      let dataSource = {};
      if(dispenseType === 'air')
        dataSource = res.data.flightOrderSettlementVO;
      if(dispenseType === 'hotel')
        dataSource = res.data.hotelOrderSettlementVO;
      if(dispenseType === 'train')
        dataSource = res.data.trainOrderSettlementVO;
      if(dispenseType === 'car')
        dataSource = res.data.carOrderSettlementVO;
      if(dispenseType === 'dining')
        dataSource = res.data.diningOrderSettlementVO;
      this.setState({ dataSource });
      return dataSource;
    }).then(res => {
      this.setState({ loading: false });
      // let params = {
      //   channel:'hly-admin',
      //   recordId: res.recordId
      // };
      // confirmSumptionService.getApportionDetail(params).then(res => {
      //   this.setState({ apportionDTOS: res.data.apportionDTOS, loading: false });
      // });
    });

    confirmSumptionService.getConfirmReasonList(dispenseId).then(res => {
      this.setState({
        reasonList: res.data.records
      })
    });

  };

  formatData = (type, data) => {
    switch (type) {
      case 'color': {
        switch (data.confirmStatus){
          case '000': return '#ccc';
          case '101': return '#1E78C8';
          case '201': return 'green';
          case '202': return 'green';
          case '203': return 'red';
        }
        break;
      }
      case 'status': {
        switch (data.confirmStatus){
          case '000': return messages('expense-16.key300')/*未推送*/;
          case '101': return messages('expense-16.key271')/*自动分发*/;
          case '102': return messages('expense-16.key268')/*手动分发*/;
          case '201': return messages('expense-16.key55')/*已确认*/;
          case '202': return messages('expense-16.key301')/*自动确认*/;
          case '203': return messages('expense-16.key302')/*反馈异常*/;
          case '204': return messages('expense-16.key303')/*逾期未确认*/;
          case '205': return messages('expense-16.key304')/*对账员处理*/;
          default : return messages('expense-16.key305')/*状态错误*/;
          break;
        }
      }
    }
  };

  onClick = type => {
    const { onConfirm, onFeedback, dispenseId } = this.props.params;
    let func = {
      'confirm': onConfirm,
      'feedback': onFeedback
    };
    if(type === 'edit') {
      this.onEditApportion();
      return;
    }
    this.setState({ loading: true });
    func[type](dispenseId).then(() => {
      this.props.close();
    }).finally(() => {
      this.setState({loading: false});
    });
  };

  onToggleAmountList = () => {
    const { animateIcon } = this.state;
    this.setState({
      animateIcon: animateIcon === 'rotate-before' ? 'rotate-after' : 'rotate-before',
      animateList: animateIcon === 'rotate-before' ? 'slide-down' : 'slide-up'
    })
  };

  onEditApportion = () => {
    const { dataSource } = this.state;
    const { dispenseId, dispenseType } = this.props.params;
    SlideFrame.open({
      title: messages('common.edit')/*编辑*/,
      content: EditConsumptionDetail,
      afterClose: (needRefresh) => needRefresh && this.getDetail(dispenseId, dispenseType),
      params: {
        vendorType: dispenseType,
        recordId: dataSource.recordId,
        totalAmount: dataSource.amount,
        currencyCode: dataSource.currency,
        employeeBearAmount: dataSource.employeeBearAmount
      },
    }, this);
  };

  render(){
    const { dispenseType, confirmType } = this.props.params;
    const { reasonList, dataSource, loading, animateIcon, animateList, apportionDTOS } = this.state;
    return(
      <Spin spinning={loading} >
        {/*<Anchor>*/}
        {/*  {*/}
        {/*    Object.keys(this.sectionList).map(key => (key !== 'costCenter' || dispenseType !== 'dining') && (*/}
        {/*      <Link href={"#confirm-consumption-detail-" + key} title={this.sectionList[key]} />*/}
        {/*    ))*/}
        {/*  }*/}
        {/*  <Link href={"#confirm-consumption-detail-apportion"} title={messages('expense-16.key434')/*分摊*!/ />*/}
        {/*  <Link href={"#confirm-consumption-detail-status"} title={messages('expense-16.key326')/*确认状态*!/ />*/}
        {/*</Anchor>*/}
        {
          dispenseType && (
            <div className="new-form confirm-consumption-detail" style={confirmType === '0' ? {paddingBottom: 60} : {}}>
            {
              Object.keys(this.sectionList).map(key => columnsListData.details[dispenseType][key] && (
                <div>
                  <div className='sub-title' id={'confirm-consumption-detail-' + key}>{this.sectionList[key]}</div>
                  {
                    columnsListData.details[dispenseType][key].map(i => (
                      <Row>
                        <Col span={6}>{i.label}</Col>
                        <Col span={16}>
                          {i.render ? i.render(dataSource[i.dataIndex], dataSource) : dataSource[i.dataIndex]}
                          {key === 'baseInfo' && i.dataIndex === 'amount' && (
                            <a className='amount-details-btn' onClick={this.onToggleAmountList}>
                              {messages('expense-16.key324')/*金额明细*/}
                              <Icon type="down" className={`animated ${animateIcon}`}/>
                            </a>
                          )}
                        </Col>
                      </Row>
                    ))
                  }
                  {
                    key === 'baseInfo' && (
                      <div
                        className={`amount-details-box animated ${animateList}`}
                        style={{height: columnsListData.amountDetails[dispenseType].length * 18 }}
                      >
                        {columnsListData.amountDetails[dispenseType].map(i =>
                          <div>
                            {i.label}: &nbsp;{i.render ? i.render(dataSource[i.dataIndex], dataSource) : dataSource[i.dataIndex]}
                          </div>
                        )}
                      </div>
                    )
                  }
                  {
                    key === 'order' && dataSource.costCenters && dataSource.costCenters.map((i, index) => (
                      <Row>
                        <Col span={6}>{messages('expense-16.key325',{arg1: index+1})/*申请单成本中心{arg1}*/}</Col>
                        <Col span={16}>{i.name || ''}</Col>
                      </Row>
                    ))
                  }
                  <Divider />
                </div>
              ))
            }
          {/*<div className='sub-title' id='confirm-consumption-detail-apportion'>*/}
          {/*  {messages('expense-16.key434')/*分摊*!/*/}
          {/*</div>*/}
          {/*<Apportion*/}
          {/*  totalAmount={dataSource.amount}*/}
          {/*  currencyCode={dataSource.currency}*/}
          {/*  employeeBearAmount={dataSource.employeeBearAmount}*/}
          {/*  disabled={true}*/}
          {/*  value={apportionDTOS}*/}
          {/*/>*/}
          <div className='sub-title' id='confirm-consumption-detail-status'>
            {messages('expense-16.key326')/*确认状态*/}
          </div>
          <Timeline>
            {
              reasonList.map(reason => (
                <Timeline.Item color={this.formatData('color', reason)}>
                  <div>
                    {reason.createdDate} &nbsp;&nbsp;
                    {this.formatData('status', reason)} &nbsp;&nbsp;
                    {(reason.userName || '') + (reason.userId || '')}
                  </div>
                  {reason.confirmReason && <div>{reason.confirmReason}</div>}
                </Timeline.Item>
              ))
            }
          </Timeline>
          {confirmType === '0' &&
            <div className="slide-footer">
              <Button type="primary" onClick={() => this.onClick('confirm')}>{messages('expense-16.key12')/*确认*/}</Button>
              <Button onClick={() => this.onClick('feedback')}>{messages('expense-16.key302')/*反馈异常*/}</Button>
              {/*<Button onClick={() => this.onClick('edit')}>{messages('common.edit')/*编辑*!/</Button>*/}
            </div>
          }
        </div>)}
      </Spin>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    options: state.login.options,
  }
}

export default connect(mapStateToProps)(ConfirmConsumptionDetail);
